package com.brand.prisd.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.widget.RadioButton;

import com.brand.prisd.R;
import com.brand.prisd.sp.MySharedPreferences;
import com.brand.prisd.utils.AlertDialogUtil;
import com.brand.prisd.utils.HomeManger;
import com.brand.prisd.view.CircleProgressBar;
import com.orhanobut.logger.Logger;
import com.tuya.smart.android.common.utils.WiFiUtil;
import com.tuya.smart.home.sdk.TuyaHomeSdk;
import com.tuya.smart.home.sdk.bean.HomeBean;
import com.tuya.smart.home.sdk.builder.ActivatorBuilder;
import com.tuya.smart.home.sdk.callback.ITuyaHomeResultCallback;
import com.tuya.smart.sdk.api.ITuyaActivator;
import com.tuya.smart.sdk.api.ITuyaActivatorGetToken;
import com.tuya.smart.sdk.api.ITuyaSmartActivatorListener;
import com.tuya.smart.sdk.bean.DeviceBean;
import com.tuya.smart.sdk.enums.ActivatorModelEnum;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ConnectActivity extends AppCompatActivity implements ITuyaHomeResultCallback {

    private String token;// 配网所需要的激活key。需要通过方法TuyaHomeSdk.getActivatorInstance().getActivatorToken ()接口获取;Token的有效期为10分钟，且配置成功后就会失效（再次配网需要重新获取）

    //超时时间
    private final int CONFIG_TIME_OUT = 100; //unit is seconds
    @BindView(R.id.cpb)
    CircleProgressBar cpb;
    @BindView(R.id.rb1)
    RadioButton rb1;
    @BindView(R.id.rb2)
    RadioButton rb2;
    @BindView(R.id.rb3)
    RadioButton rb3;
    private String wifiPsw;
    private ITuyaSmartActivatorListener mListener;
    private ITuyaActivator mTuyaActivator;


    private final int what_1 = 1;
    private int timer = 0;
    private Handler h = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case what_1:
                    int progress = (int) msg.obj;
                    cpb.setProgress(progress);
                    break;
                case 1006:
                    AlertDialogUtil.outTime(ConnectActivity.this);
                    break;
            }
            return false;
        }
    });
    private long homeId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_connect);
        ButterKnife.bind(this);
        wifiPsw = getIntent().getStringExtra("WifiPsw");
        homeId = MySharedPreferences.Build(this).getLong("homeId", -1);
        if (homeId == -1) {
            createHome();
        } else {
            TuyaHomeSdk.newHomeInstance(homeId).getHomeDetail(this);
            getActivatorToken(homeId);
        }
        HomeManger.registerTuyaHomeChangeListener();
    }

    private static boolean b = false;

    private void createHome() {
        ArrayList<String> rooms = new ArrayList<>();
        rooms.add("客厅");
        rooms.add("卧室");
        rooms.add("厨房");
        TuyaHomeSdk.getHomeManagerInstance().createHome("Hello World", 100, 20, "******", rooms, new ITuyaHomeResultCallback() {
            @Override
            public void onSuccess(HomeBean homeBean) {
                homeId = homeBean.getHomeId();
                Boolean aLong = MySharedPreferences.Build(getApplicationContext()).putLong("homeId", homeId);
                Logger.i("homeId: " + homeId);
                if (!b) {
                    TuyaHomeSdk.newHomeInstance(homeId).getHomeDetail(this);
                    getActivatorToken(homeId);
                }
            }

            @Override
            public void onError(String s, String s1) {
                Logger.e("s: " + s + "  " + "s1: " + s1);
            }
        });

    }


    private void initITuyaSmartActivatorListener() {

        //初始化回调接口
        mListener = new ITuyaSmartActivatorListener() {
            /**
             *
             * @param errorCode 1001        网络错误
             *                  1002        配网设备激活接口调用失败，接口调用不成功
             *                  1003        配网设备激活失败，设备找不到。
             *                  1004        token 获取失败
             *                  1005        设备没有上线
             *                  1006        配网超时
             * @param errorMsg 暂时没有数据，请参考errorCode。
             */
            @Override
            public void onError(String errorCode, String errorMsg) {
                Logger.e("errorCode: " + errorCode + "   " + "errorMsg: " + errorMsg);
                h.sendEmptyMessage(1006);

            }

            //设备配网成功,且设备上线（手机可以直接控制），可以通过
            @Override
            public void onActiveSuccess(DeviceBean deviceBean) {
                Logger.i("设备配网成功,且设备上线（手机可以直接控制），可以通过");
                rb2.setChecked(true);
                MySharedPreferences.Build(getApplicationContext()).putString("deviceId", deviceBean.getDevId());
//                MySharedPreferences.Build(getApplicationContext()).putString("iconUrl",deviceBean.getIconUrl());
//                MySharedPreferences.Build(getApplicationContext()).putString("deviceName",deviceBean.getName());
                rb3.setChecked(true);
                Intent intent = new Intent(ConnectActivity.this, ControlSwitchActivity.class);
                startActivity(intent);
                finish();
            }

            /**
             *
             * @param step device_find 发现设备
             *              device_bind_success 设备绑定成功，但还未上线，此时设备处于离线状态，无法控制设备。
             *
             * @param o devId (String)
             *          dev (DeviceBean)
             */
            @Override
            public void onStep(String step, Object o) {
                Logger.i("step: " + step + "  " + "o: " + o);
                rb1.setChecked(true);
            }
        };

    }


    //getActivator Token
    private void getActivatorToken(long homeId) {
        TuyaHomeSdk.getActivatorInstance().getActivatorToken(homeId, new ITuyaActivatorGetToken() {
            @Override
            public void onSuccess(String s) {
                Logger.i("s: " + s);
                token = s;
                if (!TextUtils.isEmpty(token)) {
                    initITuyaSmartActivatorListener();
                    ConfigurationParameters(token, WiFiUtil.getCurrentSSID(ConnectActivity.this), wifiPsw, ActivatorModelEnum.TY_EZ, CONFIG_TIME_OUT, ConnectActivity.this, mListener);
                } else {
                    Logger.e("********* Token为空 *********");
                }
            }

            @Override
            public void onFailure(String s, String s1) {
                Logger.e("s: " + s + "   " + "s1: " + s1);
                token = null;
            }
        });
    }

    /**
     * @param token           配网所需要的激活key。需要通过方法TuyaHomeSdk.getActivatorInstance().getActivatorToken ()接口获取;Token的有效期为10分钟，且配置成功后就会失效（再次配网需要重新获取）
     * @param ssid            配网之后，设备工作WiFi的名称。（家庭网络）
     * @param password        配网之后，设备工作WiFi的密码。（家庭网络）
     * @param activatorModel: 现在给设备配网有以下两种方式:
     *                        ActivatorModelEnum.TY_EZ: 传入该参数则进行EZ配网
     *                        ActivatorModelEnum.TY_AP: 传入该参数则进行AP配网
     * @param timeout         配网的超时时间设置，默认是100s.
     * @param context:        需要传入activity 的context.
     * @param mListener       配网回调接口
     */
    private void ConfigurationParameters(String token, String ssid, String password, ActivatorModelEnum activatorModel, int timeout, Context context, ITuyaSmartActivatorListener mListener) {
        //配置相应参数
        mTuyaActivator = TuyaHomeSdk.getActivatorInstance().newMultiActivator(new ActivatorBuilder()
                .setSsid(ssid)
                .setContext(context)
                .setPassword(password)
                .setActivatorModel(activatorModel)
                .setTimeOut(timeout)
                .setToken(token).setListener(mListener));
        //开始配置
        mTuyaActivator.start();
        startCounting();

    }

    private void startCounting() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (; timer <= 360; timer++) {
                        Message message = h.obtainMessage(what_1, timer);
                        h.sendMessage(message);
                        Thread.sleep(10000 / 36);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onStop() {
        super.onStop();
        //停止配置
        if (mTuyaActivator != null)
            mTuyaActivator.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //回调销毁
        if (mTuyaActivator != null)
            mTuyaActivator.onDestroy();

    }

    @Override
    public void onSuccess(HomeBean homeBean) {
        Logger.i("设备控制 初始化数据 成功");

    }

    @Override
    public void onError(String s, String s1) {
        Logger.e("s: " + s + "   " + "s1: " + s1);
    }

}
